<template>
  <div>
    <!-- 面包屑头部导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="#">权限管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-rol>
          <el-button type="primary" @click="addRoleDialogVisible = true"
            >添加角色</el-button
          >
        </el-rol>
      </el-row>
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              :class="[i1 == 0 ? 'bdtop' : '', 'bdbottom', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 +3Jibie-->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 2 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 3 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template v-slot="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="editRoleDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="showSetDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      @close="closeForm"
      :visible.sync="addRoleDialogVisible"
      width="50%"
    >
      <!-- 对话框主体 -->
      <el-form
        :model="addRoleForm"
        :rules="addRoleFormRules"
        ref="addRoleFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部 取消 确认  -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editRoleDialogVisible"
      width="30%"
      @close="editRoleDialogClosed"
    >
      <!-- 主体 -->
      <el-form
        :model="editRoleFrom"
        :rules="editRoleFormRules"
        ref="editRoleFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editRoleFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="用户描述">
          <el-input v-model="editRoleFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showSetDialogVisable"
      width="50%"
      @close="SetDialogVisableClose"
    >
      <!-- 分配权限对话框中间部分 -->
      <el-tree
        ref="treeref"
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all="true"
        :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <!-- 底部 -->
        <el-button @click="showSetDialogVisable = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //用户列表
      rolelist: [],
      //要添加的用户的信息
      addRoleForm: {},
      //显示要添加用户的 flag
      addRoleDialogVisible: false,
      //添加role的规则 (没有规则就是我的规则)
      addRoleFormRules: {
        roleName: [
          {
            required: true,
            message: "请输入要添加的用户的名字",
            trigger: "blur",
          },
        ],
        roleDesc: [
          {
            required: true,
            message: "请输入要添加的用户的描述",
            trigger: "blur",
          },
        ],
      },

      //修改用户节目 flag
      editRoleDialogVisible: false,
      //修改role 数据
      editRoleFrom: {
        roleName: "",
        roleDesc: "",
        id: "",
      },
      //规则
      editRoleFormRules: {},

      //分配权限对话框falg
      showSetDialogVisable: false,
      //权限列表all
      rightslist: [],
      //分配权限树形节点
      treeProps: {
        children: "children",
        label: "authName",
      },
      //默认选中的节点的数组
      defKeys: [],
      roleid:0
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //获取所有角色权限
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("查看用户列表失败");
      this.rolelist = res.data;
      // console.log(this.rolelist);
    },
    //关闭添加role的对话框
    closeForm() {
      this.$refs.addRoleFormRef.resetFields();
    },
    //添加用户对话框点确定
    async addRole() {
      const { data: res } = await this.$http.post("roles", {
        roleName: this.addRoleForm.roleName,
        roleDesc: this.addRoleForm.roleDesc,
      });
      // console.log(res);
      this.getRolesList();
      this.$refs.addRoleFormRef.resetFields();
      this.addRoleDialogVisible = false;
    },
    //打开编辑用户对话框
    async editRoleDialog(info) {
      this.editRoleDialogVisible = true;
      // console.log(info);
      const { data: res } = await this.$http.get("roles/" + info.id);
      this.editRoleFrom.id = info.id;
      this.editRoleFrom.roleName = res.data.roleName;
      this.editRoleFrom.roleDesc = res.data.roleDesc;
    },
    //关闭编辑用户对话框
    editRoleDialogClosed() {
      this.$refs.editRoleFormRef.resetFields();
      this.editRoleDialogVisible = false;
    },
    //提交 编辑用户对话框
    async editRole() {
      const { data: res } = await this.$http.put(
        "roles/" + this.editRoleFrom.id,
        {
          roleName: this.editRoleFrom.roleName,
          roleDesc: this.editRoleFrom.roleDesc,
        }
      );
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error("修改失败");
      this.$message.success("修改成功");
      this.$refs.editRoleFormRef.resetFields();
      this.editRoleDialogVisible = false;
      this.getRolesList();
    },
    //删除role
    async removeRoleById(id) {
      const { data: res } = await this.$http.delete("roles/" + id);
      // console.log(res);

      if (res.meta.status !== 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      this.getRolesList();
    },
    //删除对应用户对应的三级权限
    async removeRightById(userinfo, rightid) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") return this.$message.info("我不想删啦");

      const { data: res } = await this.$http.delete(
        `roles/${userinfo.id}/rights/${rightid}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除失败了");
      userinfo.children = res.data;
      this.$message.success("删除用户权限成功");
    },
    //分配权限对话框打开
    async showSetDialog(role) {
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200)
        return this.$message.error("获取权限列表失败");
      this.rightslist = res.data;
      console.log(this.rightslist);
      this.roleid = role.id
      this.getLeafKeys(role, this.defKeys);
      this.showSetDialogVisable = true;
    },
    //通过递归形式，获取角色所有三级权限id，并保存到defKeys数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    //关闭分配权限对话框
    SetDialogVisableClose() {
      this.defKeys = [];
    },
    //点击为角色重新分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeref.getCheckedKeys(),
        ...this.$refs.treeref.getHalfCheckedKeys()
      ];
      // console.log(keys);
      const idStr = keys.join(',')
      const {data:res} = await this.$http.post(`roles/${this.roleid}/rights`,{rids:idStr})
      if(res.meta.status!==200)return this.$message.error('分配权限错误')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.showSetDialogVisable = false
    },
  },
};
</script>

<style lang="less">
</style>